/*
 * @Author: your name
 * @Date: 2021-04-20 11:32:42
 * @LastEditTime: 2021-04-20 11:33:22
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \落地页\js\scripts.js
 */
document.documentElement.style.fontSize = '20px';

var lay_obj;
var apk_url_str = '!apk_url!';
function supportstorage() {
	if (typeof window.localStorage=='object') 
		return true;
	else
		return false;		
}
function getUrlVars(url) {
    var hash;
    var myJson = {};
    var hashes = url.slice(url.indexOf('?') + 1).split('&');
    for (var i = 0; i < hashes.length; i++) {
        hash = hashes[i].split('=');
        myJson[hash[0]] = hash[1];
    }
    return myJson;
}
function handleSaveLayout() {
	var this_obj = $(".demo");// .view
	var e = this_obj.html();
	if (!stopsave && e != window.demoHtml) {
		setCache('htmldata',getLyRowData());
		changeStructure("container-fluid", "container");
		downloadLayoutSrc()
		stopsave++;
		window.demoHtml = e;
		saveLayout();
		stopsave--;
	}
}
//获取html转json数据
function getLyRowData(){
	var this_data = [];

	var obj = $('.demo .lyrow');

	if(obj == undefined){
		return this_data;
	}

	$.each(obj,function(k,v){
		var this_width = $(v).find('input[name="row_width"]').val();
		var this_data_obj = {};
		var children_obj = $(v).find('.view_child');

		if(children_obj.length != 0){
			this_data_obj.input_width = this_width;
			this_data_obj.children = [];
			$.each(children_obj,function(k1,v1){
				var this_children_obj = {};
				this_children_obj.type = $(v1).attr('attr-type');
				this_children_obj.data = JSON.parse($(v1).attr('attr-data'));

				this_data_obj.children.push(this_children_obj);

			})
			this_data.push(this_data_obj);
		}
	})

	return this_data;
}
function getCache(name){
	return JSON.parse(localStorage.getItem(name));
}
function setCache(name,this_data){
	localStorage.setItem(name,JSON.stringify(this_data));
}

function getHtmlData(e,is_set){
	var this_type = e.attr('attr-type');
	setFromInit(this_type);
	switch (this_type) {
	    case 'pic':
	        var data = getChildrenPicData(e);
	        if(is_set == 1){
	        	setPicFrom(data);
	        }

	        break;
	    case 'lunbo':
	        var data = getChildrenLunboData(e);
	        if(is_set == 1){
	        	setLunboFrom(data);
	        }

	        break;
	    case 'video':
	        var data = getChildrenVideoData(e);
	        if(is_set == 1){
	        	setVideoFrom(data);
	        }

	        break;
	    
	    default:
	        break;
	}

}

//图片-获取数据
function getChildrenPicData(e){
	var data = {};
	var img_obj = $(e).find('.view_img');
	var this_img_src = img_obj.attr('src');
	var this_img_link = img_obj.parent('a').attr('href');
	if(this_img_src){
		data.src = this_img_src;
	}else{
		data.src = '';
	}

	if(this_img_link == 'javascript:;'){
		data.type = 0;
	}else if(this_img_link == apk_url_str){
		data.type = 2;
	}else{
		data.type = 1;
	}

	data.url = this_img_link;

	return data;
}
//图片-设置表单
function setPicFrom(data){
	var this_obj = $('#pic_handel');
	if(data.src){
		this_obj.find('.data-preview').attr('src',data.src);
		this_obj.find('.data-preview').show();
	}else{
		this_obj.find('.data-preview').hide();
	}

	this_obj.find('select[name=type]').val(data.type);
	this_obj.find('input[name=url]').val(data.url);

	lay_obj.form.render('select');

	this_obj.show();
}
//图片-保存
function savePic(e){
	
	var img_obj = $('#pic_handel').find('.data-preview');
	var img_from_obj = $('#pic_form');
	var img_from_data = getUrlVars(img_from_obj.serialize());
	var data = img_from_data;
	var this_img_src = img_obj.attr('src');
	if(this_img_src){
		data.src = this_img_src;
	}else{
		data.src = '';
	}

	if(img_from_data.type == 1){
		data.url = decodeURIComponent(img_from_data.url);

		currenteditor.find('.view_img').parent('a').attr('href',data.url);
	}else if(img_from_data.type == 2){
		currenteditor.find('.view_img').parent('a').attr('href',apk_url_str);
		data.url = apk_url_str;
	}else{
		currenteditor.find('.view_img').parent('a').attr('href','javascript:;');
		data.url = 'javascript:;';
	}

	currenteditor.find('.view_img').attr('src',this_img_src);

	currenteditor.attr('attr-data',JSON.stringify(data));
	return false;
}

//图片-获取数据
function getChildrenLunboData(e){
	var data = [];
	var item_obj = $(e).find('.item');

	$.each(item_obj,function(k,v){
		var this_data = {};
		var img_obj = $(v).find('img');
		var this_img_src = img_obj.attr('src');
		var this_img_link = img_obj.parent('a').attr('href');
		if(this_img_src){
			this_data.src = this_img_src;
		}else{
			this_data.src = '';
		}

		if(this_img_link == 'javascript:;'){
			this_data.type = 0;
		}else if(this_img_link == apk_url_str){
			this_data.type = 2;
		}else{
			this_data.type = 1;
		}

		this_data.url = this_img_link;

		data.push(this_data);
	})
	

	return data;
}
//轮播-设置表单
function setLunboFrom(data){
	var this_obj = $('#lunbo_handel');
	this_obj.find('#lunbo_form_children_div').html('');
	
	$.each(data,function(k,v){
		var example_obj = this_obj.find('.example').clone();
		example_obj.removeClass('example');

		//设置图片
		example_obj.find('.data-preview').attr('src',v.src);
		var input_src_obj = example_obj.find('input[name=src]');
		input_src_obj.val(v.src);
		input_src_obj.attr('name','src[]');
		//设置链接
		var input_url_obj = example_obj.find('input[name=url]');
		input_url_obj.val(v.url);
		input_url_obj.attr('name','url[]');
		//设置链接类型
		var input_type_obj = example_obj.find('select[name=type]');
		input_type_obj.val(v.type);
		input_type_obj.attr('name','type[]');

		$('#lunbo_form_children_div').append(example_obj);
	})
	

	lay_obj.form.render('select');
	this_obj.show();
}
//轮播-保存
function saveLunbo(e){
	
	var img_from_obj = $('#lunbo_form');
	// var img_from_data = getUrlVars(img_from_obj.serialize());
	var img_from_data = img_from_obj.serializeArray();
	var input_length = 3;

	var from_data_new = [];
	var this_data = {};

	var item_obj = currenteditor.find('.carousel-inner .active').clone(true,true);
	var slide_obj = currenteditor.find('.carousel-indicators .active').clone(true,true);

	currenteditor.find('.carousel-indicators').html('');
	currenteditor.find('.carousel-inner').html('');

	$.each(img_from_data,function(k,v){
		var this_data_name = v.name.replace('[]','');
		var this_slide_obj = slide_obj.clone(true,true);
		var this_item_obj = item_obj.clone(true,true);
		this_data[this_data_name] = v.value;

		if( k!=0 && (k+1)%input_length == 0){
			if(this_data.type == 2){
				this_data.url = apk_url_str;
			}else if(this_data.type == 1 && this_data.url){
				// this_data.url = apk_url_str;
			}else{
				this_data.url = 'javascript:;';
			}
			var this_key = (k+1)/input_length-1;
			var this_item_html = '';
			var this_slide_html = '';
			this_slide_obj.attr('data-slide-to',this_key);
			if(this_key==0){
				// this_slide_obj.addClass('active');
				this_slide_html = '<li class="active" data-slide-to="'+this_key+'" data-target="#myCarousel"></li>';
				this_item_html+='<div class="item active">';                      
			}else{
				this_slide_obj.removeClass('active');
				this_item_obj.removeClass('active');
				this_item_html+='<div class="item">';
				this_slide_html = '<li class="" data-slide-to="'+this_key+'" data-target="#myCarousel"></li>';
			}
			this_item_obj.find('a').attr('href',this_data.url);
			this_item_obj.find('img').attr('src',this_data.src);
			this_item_html+='<a href="'+this_data.url+'"><img alt="" src="'+this_data.src+'"></a></div>';

			currenteditor.find('.carousel-indicators').append(this_slide_obj);
			currenteditor.find('.carousel-inner').append(this_item_obj);

			from_data_new.push(this_data);
			this_data = {};
		}
	})

	currenteditor.attr('attr-data',JSON.stringify(from_data_new));

	return false;
}

//视频-获取数据
function getChildrenVideoData(e){
	
	var img_obj = $(e).find('.view_video');
	var data = JSON.parse($(e).attr('attr-data'));
	var this_img_src = img_obj.attr('src');

	if(this_img_src){
		data.src = this_img_src;
	}else{
		data.src = '';
	}

	return data;
}
//视频-设置表单
function setVideoFrom(data){
	var this_obj = $('#video_handel');

	if(data.src){
		this_obj.find('.data-preview').attr('src',data.src);
		this_obj.find('.data-preview').show();
	}else{
		this_obj.find('.data-preview').hide();
	}

	this_obj.find('select[name=autoplay]').val(data.autoplay);
	this_obj.find('select[name=loop]').val(data.loop);
	this_obj.find('select[name=end_event_type]').val(data.end_event_type);
	this_obj.find('input[name=url]').val(data.url);
	this_obj.find('input[name=src]').val(data.src);


	lay_obj.form.render('select');

	this_obj.show();
}
//视频-保存
function saveVideo(e){
	
	var img_obj = $('#video_handel').find('.data-preview');
	var img_from_obj = $('#video_form');
	var img_from_data = img_from_obj.serializeArray();
	var data = {};
	$.each(img_from_data,function(k,v){
		var this_data_name = v.name;
		data[this_data_name] = v.value;


		if(this_data_name == 'autoplay'
			|| this_data_name == 'loop'
		){
			if(v.value==1){
				if(this_data_name == 'autoplay'){
					currenteditor.find('.view_video').attr('muted',true);
				}
				
				currenteditor.find('.view_video').attr(this_data_name,true);
			}else{
				if(this_data_name == 'autoplay'){
					currenteditor.find('.view_video').removeAttr('muted');
				}
				currenteditor.find('.view_video').removeAttr(this_data_name);
			}
		}
	})

	if(data.end_event_type == 2){
		data.url = apk_url_str;
	}


	currenteditor.find('.view_video').attr('src',data.src);

	currenteditor.attr('attr-data',JSON.stringify(data));
	return false;
}

//初始化表单
function setFromInit(type){
	$('.post_handle').hide();
	$('#savecontent').attr('attr-type',type);

}
function remove_child(e){
	$(e).parent().remove();
}

var layouthistory; 
function saveLayout(){
	var data = layouthistory;
	if (!data) {
		data={};
		data.count = 0;
		data.list = [];
	}
	if (data.list.length>data.count) {
		for (i=data.count;i<data.list.length;i++)
			data.list[i]=null;
	}
	data.list[data.count] = window.demoHtml;
	data.count++;
	if (supportstorage()) {
		localStorage.setItem("layoutdata",JSON.stringify(data));
	}
	layouthistory = data;
	/*$.ajax({  
		type: "POST",  
		url: "/build/saveLayout",  
		data: { layout: $(".demo").html() },  
		success: function(data) {
			//updateButtonsVisibility();
		}
	});*/
}


function downloadLayout(){
	
	$.ajax({  
		type: "POST",  
		url: "/build/downloadLayout",  
		data: { layout: $('#download-layout').html() },  
		success: function(data) { window.location.href = '/build/download'; }
	});
}

function downloadHtmlLayout(){
	$.ajax({  
		type: "POST",  
		url: "/build/downloadLayout",  
		data: { layout: $('#download-layout').html() },  
		success: function(data) { window.location.href = '/build/downloadHtml'; }
	});
}

function undoLayout() {
	var data = layouthistory;
	if (data) {
		if (data.count<2) return false;
		window.demoHtml = data.list[data.count-2];
		data.count--;
		$(".demo").html(window.demoHtml);
		if (supportstorage()) {
			localStorage.setItem("layoutdata",JSON.stringify(data));
		}
		return true;
	}
	return false;
	/*$.ajax({  
		type: "POST",  
		url: "/build/getPreviousLayout",  
		data: { },  
		success: function(data) {
			undoOperation(data);
		}
	});*/
}

function redoLayout() {
	var data = layouthistory;
	if (data) {
		if (data.list[data.count]) {
			window.demoHtml = data.list[data.count];
			data.count++;
			$(".demo").html(window.demoHtml);
			if (supportstorage()) {
				localStorage.setItem("layoutdata",JSON.stringify(data));
			}
			return true;
		}
	}
	return false;
	/*
	$.ajax({  
		type: "POST",  
		url: "/build/getPreviousLayout",  
		data: { },  
		success: function(data) {
			redoOperation(data);
		}
	});*/
}

function handleJsIds() {
	handleModalIds();
	handleAccordionIds();
	handleCarouselIds();
	handleTabsIds()
}
function handleAccordionIds() {
	var e = $(".demo #myAccordion");
	var t = randomNumber();
	var n = "accordion-" + t;
	var r;
	e.attr("id", n);
	e.find(".accordion-group").each(function(e, t) {
		r = "accordion-element-" + randomNumber();
		$(t).find(".accordion-toggle").each(function(e, t) {
			$(t).attr("data-parent", "#" + n);
			$(t).attr("href", "#" + r)
		});
		$(t).find(".accordion-body").each(function(e, t) {
			$(t).attr("id", r)
		})
	})
}
function handleCarouselIds() {
	var e = $(".demo #myCarousel");
	var t = randomNumber();
	var n = "carousel-" + t;
	e.attr("id", n);
	e.find(".carousel-indicators li").each(function(e, t) {
		$(t).attr("data-target", "#" + n)
	});
	e.find(".left").attr("href", "#" + n);
	e.find(".right").attr("href", "#" + n)
}
function handleModalIds() {
	var e = $(".demo #myModalLink");
	var t = randomNumber();
	var n = "modal-container-" + t;
	var r = "modal-" + t;
	e.attr("id", r);
	e.attr("href", "#" + n);
	e.next().attr("id", n)
}
function handleTabsIds() {
	var e = $(".demo #myTabs");
	var t = randomNumber();
	var n = "tabs-" + t;
	e.attr("id", n);
	e.find(".tab-pane").each(function(e, t) {
		var n = $(t).attr("id");
		var r = "panel-" + randomNumber();
		$(t).attr("id", r);
		$(t).parent().parent().find("a[href=#" + n + "]").attr("href", "#" + r)
	})
}
function randomNumber() {
	return randomFromInterval(1, 1e6)
}
function randomFromInterval(e, t) {
	return Math.floor(Math.random() * (t - e + 1) + e)
}
function gridSystemGenerator() {
	$(".lyrow .preview input").bind("keyup", function() {
		var e = 0;
		var t = "";
		var n = $(this).val().split(" ", 12);
		$.each(n, function(n, r) {
			e = e + parseInt(r);
			t += '<div class="span' + r + ' column"></div>'
		});
		if (e == 12) {
			$(this).parent().next().children().html(t);
			$(this).parent().prev().show()
		} else {
			$(this).parent().prev().hide()
		}
	})
}
function configurationElm(e, t) {
	$(".demo").delegate(".configuration > a", "click", function(e) {
		e.preventDefault();
		var t = $(this).parent().next().next().children();
		$(this).toggleClass("active");
		t.toggleClass($(this).attr("rel"))
	});
	$(".demo").delegate(".configuration .dropdown-menu a", "click", function(e) {
		e.preventDefault();
		var t = $(this).parent().parent();
		var n = t.parent().parent().next().next().children();
		t.find("li").removeClass("active");
		$(this).parent().addClass("active");
		var r = "";
		t.find("a").each(function() {
			r += $(this).attr("rel") + " "
		});
		t.parent().removeClass("open");
		n.removeClass(r);
		n.addClass($(this).attr("rel"))
	})
}
function removeElm() {
	$(".demo").delegate(".remove", "click", function(e) {
		e.preventDefault();
		$(this).parent().remove();
		if (!$(".demo .lyrow").length > 0) {
			clearDemo()
		}
	})
}
function clearDemo() {
	$(".demo").empty();
	layouthistory = null;
	if (supportstorage())
		localStorage.removeItem("layoutdata");
}
function removeMenuClasses() {
	$("#menu-layoutit li button").removeClass("active")
}
function changeStructure(e, t) {
	$("#download-layout ." + e).removeClass(e).addClass(t)
}
function cleanHtml(e) {
	if($(e).children().hasClass('view_child')){
		var this_obj = $(e).html();
	}else{
		var this_obj = $(e).children().html();
	}
	$(e).parent().append(this_obj)
}
function downloadLayoutSrc() {
	var e = "";
	$("#download-layout").children().html($(".demo").html());

	var t = $("#download-layout").children();

	t.find(".preview, .configuration, .drag, .remove").remove();
	t.find(".lyrow").addClass("removeClean");
	t.find(".box-element").addClass("removeClean");
	t.find(".lyrow .lyrow .lyrow .lyrow .lyrow .removeClean").each(function() {
		cleanHtml(this)
	});
	
	t.find(".lyrow .lyrow .lyrow .lyrow .removeClean").each(function() {
		cleanHtml(this)
	});

	t.find(".lyrow .lyrow .lyrow .removeClean").each(function() {
		cleanHtml(this)
	});
	t.find(".lyrow .lyrow .removeClean").each(function() {
		cleanHtml(this)
	});

	t.find(".lyrow .removeClean").each(function() {
		cleanHtml(this)
	});

	t.find(".removeClean").each(function() {
		cleanHtml(this)
	});

	t.find(".removeClean").remove();

	$("#download-layout .column").removeClass("ui-sortable");
	$("#download-layout .row-fluid").removeClass("clearfix").children().removeClass("column");
	if ($("#download-layout .container").length > 0) {
		changeStructure("row-fluid", "row")
	}
	formatSrc = $.htmlClean($("#download-layout").html(), {
		format: true,
		allowedAttributes: [
			["id"]
			,["class"]
			,["data-toggle"]
			,["data-target"]
			,["data-parent"]
			,["role"]
			,["data-dismiss"]
			,["aria-labelledby"]
			,["aria-hidden"]
			,["data-slide-to"]
			,["data-slide"]
			,["attr-data"]
			,["attr-type"]
			,["autoplay"]
			,["loop"]
			,["controls"]
			,["src"]
			,["muted"]
		],
	});
	$("#download-layout").html(formatSrc);
	$("#downloadModal textarea").empty();
	$("#downloadModal textarea").val(formatSrc)
}

var currentDocument = null;
var timerSave = 1000;
var stopsave = 0;
var startdrag = 0;
var demoHtml = $(".demo").html();
var currenteditor = null;
$(window).resize(function() {
	$("body").css("min-height", $(window).height() - 90);
	$(".demo").css("min-height", $(window).height() - 160)
});

function restoreData(){
	if (supportstorage()) {
		layouthistory = JSON.parse(localStorage.getItem("layoutdata"));
		if (!layouthistory) return false;
		window.demoHtml = layouthistory.list[layouthistory.count-1];
		if (window.demoHtml){
			$(".demo").html(window.demoHtml);
			add_event();
		}
	}
}

function initContainer(){
	$(".demo, .demo .column").sortable({
		connectWith: ".column",
		opacity: .35,
		handle: ".drag",
		start: function(e,t) {
			if (!startdrag) stopsave++;
			startdrag = 1;
		},
		stop: function(e,t) {
			if(stopsave>0) stopsave--;
			startdrag = 0;
			handleSaveLayout();
		}
	});
	configurationElm();
}
$(document).ready(function() {
	// CKEDITOR.disableAutoInline = true;
	restoreData();
	// var contenthandle = CKEDITOR.replace( 'contenteditor' ,{
	// 	language: 'zh-cn',
	// 	contentsCss: ['/static/layuiadmin/other/channel_page/css/bootstrap-combined.min.css'],
	// 	allowedContent: true
	// });
	$("body").css("min-height", $(window).height() - 90);
	$(".demo").css("min-height", $(window).height() - 160);
	/*工具栏布局拖动*/
	$(".sidebar-nav .lyrow").draggable({
		connectToSortable: ".demo",
		helper: "clone",
		handle: ".drag",
		start: function(e,t) {
			if (!startdrag) stopsave++;
			startdrag = 1;
		},
		drag: function(e, t) {
			t.helper.width(400)
		},
		stop: function(e, t) {
			$(".demo .column").sortable({
				opacity: .35,
				connectWith: ".column",
				start: function(e,t) {
					if (!startdrag) stopsave++;
					startdrag = 1;
				},
				stop: function(e,t) {
					if(stopsave>0) stopsave--;
					startdrag = 0;
				}
			});
			if(stopsave>0) stopsave--;
			startdrag = 0;
			handleSaveLayout();
		}
	});
	/*工具栏组件拖动*/
	$(".sidebar-nav .box").draggable({
		connectToSortable: ".column",
		helper: "clone",
		handle: ".drag",
		start: function(e,t) {
			if (!startdrag) stopsave++;
			startdrag = 1;
		},
		drag: function(e, t) {
			t.helper.width(400)
		},
		stop: function() {
			handleJsIds();
			if(stopsave>0) stopsave--;
			startdrag = 0;
			handleSaveLayout();
		}
	});
	initContainer();
	$('body.edit .demo').on("click","[data-target=#editorModal]",function(e) {
		e.preventDefault();
		currenteditor = $(this).parent().parent().find('.view');
		// var eText = currenteditor.html();
		// contenthandle.setData(eText);
		currenteditor.attr('attr-data',getHtmlData(currenteditor,1));

	});
	$("#savecontent").click(function(e) {
		e.preventDefault();
		var this_type = $(this).attr('attr-type');

		switch (this_type) {
		    case 'pic':
		        savePic($(this));
		        break;
		    case 'lunbo':
		        saveLunbo($(this));
		        break;
		    case 'video':
		        saveVideo($(this));
		        break;
		     
		    default:
		        break;
	}
		// currenteditor.html(contenthandle.getData());
	});
	$("[data-target=#downloadModal]").click(function(e) {
		e.preventDefault();
		downloadLayoutSrc();
	});
	$("[data-target=#shareModal]").click(function(e) {
		e.preventDefault();
		handleSaveLayout();

	});
	$("#download").click(function() {
		downloadLayout();
		return false
	});
	$("#downloadhtml").click(function() {
		downloadHtmlLayout();
		return false
	});
	$("#edit").click(function() {
		$("body").removeClass("devpreview sourcepreview");
		$("body").addClass("edit");
		removeMenuClasses();
		$(this).addClass("active");
		return false
	});
	$("#clear").click(function(e) {
		e.preventDefault();
		clearDemo()
	});
	$("#devpreview").click(function() {
		$("body").removeClass("edit sourcepreview");
		$("body").addClass("devpreview");
		removeMenuClasses();
		$(this).addClass("active");
		return false
	});
	$("#sourcepreview").click(function() {
		$("body").removeClass("edit");
		$("body").addClass("devpreview sourcepreview");
		removeMenuClasses();
		$(this).addClass("active");
		return false
	});
	$("#fluidPage").click(function(e) {
		e.preventDefault();
		changeStructure("container", "container-fluid");
		$("#fixedPage").removeClass("active");
		$(this).addClass("active");
		downloadLayoutSrc()
	});
	$("#fixedPage").click(function(e) {
		e.preventDefault();
		changeStructure("container-fluid", "container");
		$("#fluidPage").removeClass("active");
		$(this).addClass("active");
		downloadLayoutSrc()
	});
	$(".nav-header").click(function() {
		$(".sidebar-nav .boxes, .sidebar-nav .rows").hide();
		$(this).next().slideDown()
	});
	$('#undo').click(function(){
		stopsave++;
		if (undoLayout()) initContainer();
		stopsave--;
	});
	$('#redo').click(function(){
		stopsave++;
		if (redoLayout()) initContainer();
		stopsave--;
	});
	removeElm();
	gridSystemGenerator();
	// handleSaveLayout();
	setInterval(function() {
		handleSaveLayout()
	}, timerSave)
})